package com.shenyue.nbtownlet.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.drawable.AnimationDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.util.StringUtil;

public class Wait {
    private static Wait _sharedInstance = null;
    private Dialog dialog = null;

    public static Wait sharedInstance() {
        if (_sharedInstance == null)
            _sharedInstance = new Wait();
        return _sharedInstance;
    }

    public void start(Context context) {
        start(context, null);
    }

    public void start(Context context, String msg) {
        if (dialog != null) {
            TextView tv = dialog.findViewById(R.id.com_boingpay_dialog_iv_loading_label);
            if (!StringUtil.isNull(msg))
                tv.setText(msg);
            return;
        }
        dialog = new Dialog(context, R.style.com_boingpay_custom_progress_dialog);
        View actionView = LayoutInflater.from(context).inflate(R.layout.com_boingpay_dialog_progress, null);
        TextView tv = actionView.findViewById(R.id.com_boingpay_dialog_iv_loading_label);
        if (!StringUtil.isNull(msg))
            tv.setText(msg);
        ImageView loadingImage = actionView.findViewById(R.id.com_boingpay_dialog_iv_loading);
        if (loadingImage.getBackground() instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) loadingImage.getBackground();
            animationDrawable.start();
        }
        dialog.setContentView(actionView);
        dialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                stop();
            }
        });
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);
        dialog.show();
    }

    public void stop() {
        try {
            if (isShow()) {
                dialog.dismiss();
                dialog = null;
            }
        } catch (Exception e) {
            dialog = null;
        }
    }

    public boolean isShow() {
        if (dialog != null && dialog.isShowing())
            return true;
        else return false;
    }
}
